<?php

// phpMyRealty 3
//
// File Name: functions.php
// File Location : ./includes/
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com


// --------------------------------------------------------------------------
// ERROR()
// error function outputs the error type and description
// ex. error ('Critical Error', 'Unable to connect to mysql database');

function error ( $errortype, $errormessage )

 {

  echo '<b><strong>' . $errortype . '</strong></b>
  <br /><br />' . $errormessage . ' <br />';

  exit(0);

 }


// --------------------------------------------------------------------------
// VALID_EMAIL()
// Validates the email

 function valid_email ( $address )

 {

  if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $address))
   return false;
  else
   return true;

 }


// --------------------------------------------------------------------------
// GETNAMEBYID()
// This function returns the name field according to the
// ID, suitable for simple tables like LOCATIONS, TYPES etc.

function getnamebyid ( $name, $id )

 {

  global $db;
  global $cookie_language;
  global $language_in;

  if ( isset($id) && $id != 0 && !empty($id) )

   {

    $sql = 'SELECT ' . $language_in . ', name FROM ' . $name . ' WHERE id = "' . $id . '" LIMIT 1';
    $r = $db->query ($sql) or error ('Critical Error', mysql_error () );
    $f = $db->fetcharray ($r);
    
    if ($f[0] == '')
    	return $f['name'];
   	else
    	return $f[0];

   }

  else

   return '';

 }

 // --------------------------------------------------------------------------
// show_custom_value()
// This function returns the name field according to the
// ID, suitable for custom fields and values.
function show_custom_value ( $db, $id, $table )
{
  if ( $id == '' )
   {
       return '';
   }

   if ($table == VALUES_TABLE) {
   	$whereColumn = 'id';
   } else {
   	$whereColumn = 'field';
   }
   global $language_in;
   $field = $language_in;

    $sql = 'SELECT name, '.$field.' FROM ' . $table . ' WHERE ' . $whereColumn . ' = "' . $id . '" LIMIT 1';
    $r = $db->query ($sql) or error ('Critical Error', mysql_error () );
    $f = $db->fetcharray ($r);
    return (strlen(trim($f[$field])) == 0) ? $f['name'] : $f[$field];

}

// --------------------------------------------------------------------------
// VALIDATEWEBSITE()
// This function returns the URL with http:// prefix added
// if it's not there.

function validatewebsite ( $id, $url = '' )

 {

  global $lang;

  if ( !empty($url) && $url != 'n/a' )
   {
    if ( ereg ( "http://", $url ) )
     $output = '<a href="' . $url . '" target="new" >';
    elseif ( ereg ( "https://", $url ) )
     $output = '<a href="' . $url . '" target="new" >';
    elseif ( ereg ( "ftp://", $url ) )
     $output = '<a href="' . $url . '" target="new" >';
    else
     $output = '<a href="http://' . $url . '" target="new">';
   }

  else

   $output = '<a href="#" target="new">';

  return $output;

 }

// --------------------------------------------------------------------------
// VALIDATEEMAIL()
// This function generates URL to the email form

function validateemail ( $id, $email = '', $listing = '' )

 {

  global $lang, $conf;

  if (empty($listing)) {
  if ($conf['rewrite'] == 'ON')
   $output = '<a href="' . URL . '/Mail/' . $id . '.html">';
  else
   $output = '<a href="' . URL . '/sendmessage.php?id=' . $id . '">';
  }
  else {
  if ($conf['rewrite'] == 'ON')
   $output = '<a href="' . URL . '/Mail/' . $id . '-' . $listing. '.html">';
  else
   $output = '<a href="' . URL . '/sendmessage.php?id=' . $id . '&listing=' . $listing . '">';
  }

  return $output;

 }

// --------------------------------------------------------------------------
// VIEWUSERLISTINGS()
// This function generates URLs to the user's listings

function viewuserlistings ( $id )

 {

  global $db;
  global $lang;
  global $conf;

  $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE userid = "' . $id . '" AND approved = 1 ORDER BY title';
  $r = $db->query ( $sql ) or error ('Critical Error', mysql_error () );

  if ($db->numrows($r) > 0)
   $output = $lang['Realtor_Listings'];
  else
   $output = '';

  while ($f = $db->fetcharray ($r))
   {

    if ($conf['rewrite'] == 'ON')
     $output.= ' - <a href="' . URL . '/Listing/' . rewrite ( getnamebyid ( TYPES_TABLE, $f['type'] ) ) . '/' . $f['id'] . '_' . rewrite($f['title']) . '.html">' . $f['title'] . '</a><br />';
    else
     $output.= ' - <a href="' . URL . '/viewlisting.php?id=' . $f['id'] . '">' . $f['title'] . '</a><br />';

   }

  if ($db->numrows($r) > 0)
   $output.= '<br /> (<a href="' . URL . '/search.php?userid=' . $id . '"> ' . $lang['Realtor_View_All_Listings'] . '</a> )';

  return $output;

 }


// --------------------------------------------------------------------------
// SHOW_MULTIPLE()
// This function generates list of all the items
// in (x:y:z) format taken from the database 

function show_multiple ( $table_name, $selected = '' ){

 global $db;
 global $cookie_language;
 global $language_in;
 
 if ((isset($selected)) and (!is_array($selected)))
  $selected = explode (':' , $selected);

 $sql = 'SELECT id, ' . $language_in . ', name FROM ' . $table_name . ' ORDER BY ' . $language_in;
 $r = $db->query ($sql) or error ('Critical Error', mysql_error () );
  $output = '';
 $i = 1;
  while ($f = $db->fetcharray ($r) ) {
  if ((!is_array($selected) && $f['id'] == $selected) OR (is_array($selected) && in_array($f['id'], $selected))) {
   
   	if ($f[1] == '')
   		$f[1] = $f['name'];
   
   if (count($selected) == $i)
   {
   	$output.= $f[1] . ' ';
   } else {
    $output.= $f[1] . ', ';
    $i++;
   }
   }
  }
return $output;

}

// --------------------------------------------------------------------------
// UPDATE_CATEGORIES()
// This function increments the counter in the property_types
// table if listing was just added or changes the counters
// according to the type change if listing was updated or removes

function update_categories ( $was = '', $is = '' )

 {

  global $db;

  // if listing was just added $was variable is not set
  if (empty($was) & !empty($is))
   {
    $sql = 'UPDATE ' . TYPES_TABLE . ' SET counter=counter+1 WHERE id = "' . $is . '" LIMIT 1';
    $db->query ($sql) or error ('Critical Error' , mysql_error ());
   }

  // if listing was updated, all variables are set
  if (!empty($was) & !empty($is))
   {

    $sql = 'UPDATE ' . TYPES_TABLE . ' SET counter=counter-1 WHERE id = "' . $was . '" LIMIT 1';
    $db->query ($sql) or error ('Critical Error' , mysql_error ());

    $sql = 'UPDATE ' . TYPES_TABLE . ' SET counter=counter+1 WHERE id = "' . $is . '" LIMIT 1';
    $db->query ($sql) or error ('Critical Error' , mysql_error ());

   }

  // if listing was removed, $is is not set
  if (!empty($was) & empty($is))
   {
    $sql = 'UPDATE ' . TYPES_TABLE . ' SET counter=counter-1 WHERE id = "' . $was . '" LIMIT 1';
    $db->query ($sql) or error ('Critical Error' , mysql_error ());
   }

 }

// --------------------------------------------------------------------------
// IF_EMPTY()
// This function returns 'n/a' for the value if it is empty

function if_empty ( $value )

 {

  if ($value == '' || $value == '0')
   return '';
  else
   return $value;

 }

// --------------------------------------------------------------------------
// NEWITEM()
// This function returns TRUE if this is a new listing
// (added during last $days days)

function newitem ( $table, $id, $days )

 {

  global $db, $lang;

  $sql = 'SELECT id FROM ' . $table . ' WHERE id = "' . $id . '" AND (TO_DAYS(NOW()) - TO_DAYS(date_added)) <= "' . $days . '" ';
  $r = $db->query ( $sql ) or error ('Critical Error', mysql_error () );

  if ($db->numrows ($r) > 0)
  return $lang['Listing_New_Mark'];

 }

// --------------------------------------------------------------------------
// UPDATEDITEM()
// This function returns TRUE if this is an updated listing
// (updated during last X days)

function updateditem ( $table, $id, $days )

 {

  global $db, $lang;

  $sql = 'SELECT id FROM ' . $table . ' WHERE id = "' . $id . '" AND (TO_DAYS(NOW()) - TO_DAYS(date_updated)) <= "' . $days . '" ';
  $r = $db->query ( $sql ) or error ('Critical Error', mysql_error () );

  if ($db->numrows ($r) > 0)
  return $lang['Listing_Updated_Mark'];

 }

// --------------------------------------------------------------------------
// TOPITEM()
// This function returns TRUE if this is a TOP user
// (have rating => 4.5 with at least 5 votes)

function topitem ( $rating, $votes )

 {

  global $lang;

  if ($votes > 0)
   {
    if (($rating/$votes) >= 4.5 && $votes >= 5)
    return $lang['Realtor_Top_Mark'];
   }

 }

// --------------------------------------------------------------------------
// FEATUREDITEM()
// This function returns TRUE if this is a featured listing

function featureditem ( $featured )

 {

  global $lang;

  if ($featured == 'A')
   {
    return $lang['Listing_Featured_Mark'];
   }

 }

// ----------------------------------------------------------------------
// REMOVEUSERLISTING()
// removes listing and all associated information from the database
//

function removeuserlisting ( $id )

 {

  global $db;

  $sql = 'SELECT approved, id, type FROM ' . PROPERTIES_TABLE . ' where id = "' . $id . '" ';
  $r = $db->query($sql) or error ('Critical Error' , 'Can\'t SELECT FROM listings DATABASE');

  while ($f = $db->fetcharray($r))

  {

   removelistingimage('images', $f['id']);

   banner_remove('banners', $f['id']);

   if ($f['approved'] == 1) update_categories($f['type'], '');

  }

  $sql = 'DELETE FROM ' . PROPERTIES_TABLE . ' where id = "' . $id . '" ';
  $db->query($sql) or error ('Critical Error' , 'Can\'t remove listings record');

  $sql = 'SELECT id FROM ' . GALLERY_TABLE . ' where listingid = "' . $id . '" ';
  $r = $db->query($sql) or error ('Critical Error' , 'Can\'t SELECT FROM gallery DATABASE');

  while ($f = $db->fetcharray($r))
   {
    removelistingimage('gallery', $f['id']);
   }

  $sql = 'DELETE FROM ' . GALLERY_TABLE . ' where listingid = "' . $id . '" ';
  $db->query($sql) or error ('Critical Error' , 'Can\'t remove gallery record');

  $sql = 'DELETE FROM ' . FEATURED_TABLE . ' where id = "' . $id . '" ';
  $db->query($sql) or error ('Critical Error' , 'Can\'t remove user record in featured table');

 }

//

function removelistingimage ( $folder, $id)

 {

  global $db;

  if ( file_exists ( PATH . '/' . $folder . '/' . $id . '.jpg' ))
   unlink (PATH . '/' . $folder . '/' . $id . '.jpg' );

  if ( file_exists ( PATH . '/' . $folder . '/' . $id . '-resampled.jpg' ))
   unlink (PATH . '/' . $folder . '/' . $id . '-resampled.jpg' );

  // Updating databases

  if ($folder == 'images')
   {
    $sql = 'UPDATE ' . PROPERTIES_TABLE . ' SET image_uploaded = 0 WHERE id = "' . $id . '" LIMIT 1';
    $db->query($sql) or error ('Critical Error', mysql_error());
   }

 }


if(!function_exists('str_split')) {

    function str_split($string,$string_length=1) {

        if(strlen($string)>$string_length || !$string_length) {

            do {

                $c = strlen($string);

                $parts[] = substr($string,0,$string_length);

                $string = substr($string,$string_length);

            } while($string !== false);

        } else {

            $parts = array($string);

        }

        return $parts;

    }

}

function pmr_number_format($number, $decimals = 0)
{
    global $conf;
    $dec_point = $conf['decimal_point'];
    $thousands_sep = $conf['1000_separator'];
    return number_format($number, $decimals, $dec_point, $thousands_sep);
}

?>